<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
// import { getActiveMachines } from "@/api/file";
// import { ElMessage } from "element-plus";
import Edit from "@iconify-icons/ep/edit";
import Plus from "@iconify-icons/ep/plus";
import Delete from "@iconify-icons/ep/delete";
import AddDialog from "./addDialog.vue";
import yamlLabel from "./yamlLabel.json";

defineOptions({
  name: "formItem"
});

let timer = null;
const props = defineProps(["label", "data", "index", "parent", "projectName"]);
const emit = defineEmits(["data-change", "label-change", "label-del"]);
const data = ref(props.data);
const title = ref(props.label);
const isEditTitle = ref(false);
const dialogVisible = ref(false);
const reflesh = ref(true);
// const selectLoading = ref(false);
// const distributedOptions = ref([]);
const dataType = computed(() => {
  if (props.data === null) return "null";
  else if (props.data instanceof Array) return "array";
  else if (props.data instanceof Object) return "object";
  else return typeof props.data;
});

const isDisable =
  props.label == "Errors Writer>filename" ||
    props.label == "KPI Writer>filename" ||
    props.label == "Res_CPU>filename" ||
    props.label == "Res_Memory>filename" ||
    props.label == "script"
    ? ref(true)
    : ref(false);

watch(
  data,
  (newVal, oldVal) => {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      console.log(`${props.label}: ${newVal}, ${oldVal}`);
      if (props.index !== undefined) {
        emit("data-change", props.label, newVal, props.index);
      } else {
        emit("data-change", props.label, newVal);
      }
    }, 500);
  },
  { deep: true }
);

const labelChange = () => {
  isEditTitle.value = !isEditTitle.value;
  if (props.label == title.value) return;
  emit("label-change", props.label, title.value, data.value);
};

const changeData = (
  key: string | number,
  value: any,
  index: string | number
) => {
  if (dataType.value == "object") {
    data.value[key] = value;
  } else if (dataType.value == "array") {
    data.value[index][key] = value;
  }
};

const changeLabel = (
  oldLabel: string | number,
  newLabel: string | number,
  newData: any
) => {
  data.value[newLabel] = newData;
  delete data.value[oldLabel];
};

const delLabel = (oldLabel: string | number) => {
  delete data.value[oldLabel];
};

const addItem = (arr: any[]) => {
  switch (props.label) {
    case "scenarios":
      addScenarios(arr);
      break;
    case "execution":
      addExecution(arr);
      break;
    default:
      break;
  }
};

const addScenarios = async (keyList: any[]) => {
  keyList.forEach((item: string | number) => {
    data.value[item] = {
      modifications: {
        "set-prop": {
          "Errors Writer>filename": `\${Jtl_DIR}\\${item}_error.jtl`,
          "KPI Writer>filename": `\${Jtl_DIR}\\${item}_kpi.jtl`,
          "Res_CPU>filename": `\${Jtl_DIR}\\${item}_cpu.jtl`,
          "Res_Memory>filename": `\${Jtl_DIR}\\${item}_memory.jtl`,
          "Runtime Controller>RunTime.seconds": `300`
        }
      },
      script: `\${testplans_DIR}\\${item}.jmx`
    };
  });
  reflesh.value = false;
  await nextTick();
  reflesh.value = true;
};

const delScenarios = () => {
  emit("label-del", props.label);
};

const addExecution = (newData: any) => {
  console.log(newData);
  data.value = data.value.concat(newData);
};

const delExecution = async (index: any) => {
  data.value.splice(index, 1);
  reflesh.value = false;
  await nextTick();
  reflesh.value = true;
};

// const handleVisibleChange = async (visible: boolean) => {
//   if (visible) {
//     try {
//       selectLoading.value = true;
//       const res = await getActiveMachines();
//       selectLoading.value = false;
//       if (res.success) {
//         distributedOptions.value = res.data;
//         ElMessage.success(res.msg);
//       } else {
//         ElMessage.error(res.msg);
//       }
//     } catch (error) {
//       selectLoading.value = false;
//       ElMessage.error(error);
//     }
//   }
// };

const handleBackspace = event => {
  event.preventDefault();
};
</script>

<template>
  <el-card v-if="(dataType == 'array' || dataType == 'object') && reflesh" class="warp" shadow="hover">
    <div class="header">
      <div :style="{ 'border-left-color': 'rgb(35, 98, 251)' }" class="mark" />
      <div v-if="!isEditTitle" class="title">
        {{ yamlLabel[props.label] || props.label }}
        <el-tooltip v-if="props.parent == 'scenarios'" class="box-item" effect="dark" content="编辑" placement="top">
          <el-button circle size="small" class="title-button" type="primary" @click="isEditTitle = !isEditTitle">
            <IconifyIconOffline :icon="Edit" />
          </el-button>
        </el-tooltip>
        <el-popconfirm v-if="props.parent == 'scenarios'" title="你确定要删除此项吗?" width="200" @confirm="delScenarios">
          <template #reference>
            <div>
              <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-button circle size="small" class="title-button" type="danger">
                  <IconifyIconOffline :icon="Delete" />
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-popconfirm>
        <el-tooltip v-if="props.label == 'scenarios' || props.label == 'execution'" class="box-item" effect="dark"
          content="新增" placement="top">
          <el-button circle size="small" class="title-button" @click="dialogVisible = true">
            <IconifyIconOffline :icon="Plus" />
          </el-button>
        </el-tooltip>
      </div>
      <el-input v-else class="header-input" v-model="title" placeholder="Please input">
        <template #append>
          <el-button type="primary" @click="labelChange"> 确定 </el-button>
        </template>
      </el-input>
    </div>
    <div class="content">
      <template v-if="dataType == 'array'">
        <el-collapse>
          <el-collapse-item :title="item['scenario']" v-for="(item, index) in props.data" :key="index">
            <div class="array-div">
              <el-card class="warp" shadow="hover">
                <!-- <FormItem
                  v-for="(value, key) in item"
                  :label="key"
                  :data="value"
                  :key="key"
                  :index="index"
                  :parent="props.label"
                  @data-change="changeData"
                /> -->
                <FormItem label="scenario" :data="item['scenario']" :index="index" :parent="props.label"
                  @data-change="changeData" />
                <FormItem label="concurrency" :data="item['concurrency']" :index="index" :parent="props.label"
                  @data-change="changeData" />
                <FormItem label="ramp-up" :data="item['ramp-up']" :index="index" :parent="props.label"
                  @data-change="changeData" />
                <FormItem label="targettime" :data="item['targettime']" :index="index" :parent="props.label"
                  @data-change="changeData" />
                <!-- <FormItem
                  label="distributed"
                  :data="item['distributed']"
                  :index="index"
                  :parent="props.label"
                  @data-change="changeData"
                /> -->
              </el-card>
              <el-popconfirm title="你确定要删除此项吗?" width="200" @confirm="delExecution(index)">
                <template #reference>
                  <div>
                    <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                      <el-button circle size="small" style="margin-left: 10px" type="danger">
                        <IconifyIconOffline :icon="Delete" />
                      </el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-popconfirm>
            </div>
          </el-collapse-item>
        </el-collapse>
      </template>
      <template v-else-if="dataType == 'object'">
        <FormItem v-for="(value, key) in props.data" :label="key" :data="value" :key="key" :parent="props.label"
          @data-change="changeData" @label-change="changeLabel" @label-del="delLabel" />
      </template>
    </div>
    <AddDialog v-model="dialogVisible" :projectName="props.projectName" :type="props.label" @submit="addItem" />
  </el-card>
  <el-form-item v-else-if="!isDisable" :label="yamlLabel[props.label] || props.label" :key="props.label"
    :prop="props.label">
    <!-- <el-select
      v-if="props.label == 'distributed'"
      v-model="data"
      placeholder="请选择"
      :loading="selectLoading"
      multiple
      @visible-change="handleVisibleChange"
    >
      <el-option
        v-for="item in distributedOptions"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select> -->
    <el-input v-if="dataType == 'string'" v-model="data" :disabled="props.label == 'scenario'" />
    <el-input-number v-if="dataType == 'number' || dataType == 'null'" v-model="data" :value-on-clear="0" :min="0" />
    <!-- <el-input-number
      v-if="dataType == 'number' || dataType == 'null'"
      v-model="data"
      :min="0"
      :value-on-clear="0"
      @keydown.backspace.native="handleBackspace"
    /> -->
    <el-switch v-if="dataType == 'boolean'" v-model="data" active-text="true" inactive-text="False" />
    <span v-if="props.label == 'ramp-up'" style="margin-left: 5px">s</span>
    <span v-if="props.label == 'targettime'" style="margin-left: 5px">ms</span>
  </el-form-item>
</template>

<style lang="scss" scoped>
.warp {
  flex-grow: 1;
  margin-bottom: 20px;
}

.header {
  display: flex;
  align-items: center;
  padding: 5px 15px;

  .header-input {
    margin: 0 10px;
  }
}

.mark {
  height: 14px;
  border-left-style: solid;
  border-left-width: 4px;
  border-radius: 2px;
}

.title {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  margin-left: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #333;

  .title-icon {
    margin-left: 10px;
    color: rgb(35 98 251);
  }

  .title-button {
    margin-left: 10px;
  }
}

.content {
  padding: 0 20px;

  .array-div {
    display: flex;
    align-items: center;
  }
}
</style>
